package com.amkai.aes.webservice.binary.objecthandler.casehistory;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;

import com.amkai.aes.aescommon.service.binary.job.casehistory.ChartDocumentsJob;
import com.amkai.aes.aescommon.service.binary.job.casehistory.ChartDocumentsResult;
import com.amkai.aes.generatedbeans.cdmcasehistory.items.ChartDocument;
import com.amkai.aes.generatedbeans.cdmcasehistory.items.ChartDocumentAppointmentTypeAssociation;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

public class ChartDocumentsJobHandler implements JobObjectHandler<ChartDocumentsJob, Serializable, ChartDocumentsResult> {

	private static final Log log = LogFactory.getLog(ChartDocumentsJobHandler.class);

	private static String query = "SELECT chartDocument FROM ChartDocument chartDocument ";
	
	private static String where = "WHERE chartDocument.active = :required";
	
	@SuppressWarnings("unchecked")
	@Override
	public ChartDocumentsResult process(ChartDocumentsJob job, Serializable object) throws Exception {
		ChartDocumentsResult result = new ChartDocumentsResult();

		String queryString = ChartDocumentsJobHandler.query;
		boolean needWhere = (job.getRequired() != null);

		if (needWhere) {
			queryString = queryString + ChartDocumentsJobHandler.where;
		}
		
		SessionManager sm = SiteManager.Start();
		sm.openSession();
		try {
			Query query = sm.execute(queryString);
			if (needWhere) {
				query.setParameter("required", job.getRequired());
			}
			
			List<ChartDocument> chartDocuments = (List<ChartDocument>) query.list();
			if (chartDocuments != null && chartDocuments.size() > 0) {
				if (job.getAppointmentTypeId() != null) {
					for (ChartDocument chartDocument : chartDocuments) {
						if (chartDocument.getChartDocumentAppointmentTypeAssociations() != null) {
							for (ChartDocumentAppointmentTypeAssociation chartDocumentAppointmentTypeAssociation : chartDocument.getChartDocumentAppointmentTypeAssociations()) {
								if (chartDocumentAppointmentTypeAssociation.getAppointmentType().getId().equals(job.getAppointmentTypeId())) {
									result.getChartDocuments().add(chartDocument);
								}
							}
						}
					}
				} else {
					result.getChartDocuments().addAll(chartDocuments);
				}
			}
			
		} catch (Exception exception) {
			ChartDocumentsJobHandler.log.error("Chart Documents Job", exception);
			exception.printStackTrace();
			throw exception;
		} finally {
			sm.closeSession();
		}
		return result;
	}

}
